<!-- 分页表格组件 -->
<script lang="ts" setup>
import type { IEmits, PropsType } from './Types';

import { computed, ref, useAttrs, watch } from 'vue';

const emits = defineEmits<IEmits>();
const ElTableRef = ref(null);
const PaginationRef = ref(null);
const attrs: PropsType = useAttrs();
const isShowPager = computed((): boolean => {
  return !!attrs.pager?.page && !!attrs.pager?.limit;
});

watch(
  () => [attrs.pager?.page, attrs.pager?.limit],
  (newVal, oldVal) => {
    if (newVal[0] === oldVal[0] && newVal[1] === oldVal[1]) {
      return;
    }
    if (newVal[1] !== oldVal[1] && oldVal[0] !== 1) {
      attrs.pager.page = 1;
      return;
    }
    emits('pageChange', attrs.pager);
  },
);

defineExpose({
  ElTableRef,
  PaginationRef,
});
</script>

<template>
  <div class="card-box p-5">
    <!-- table 的背景颜色，暗黑模式太丑了 -->
    <!-- :header-cell-style="attrs.headerCellStyle || { background: '#E8E9ED' }" -->
    <el-table v-bind="attrs" ref="ElTableRef" v-loading="attrs.loading">
      <!-- 插槽支持 -->
      <template #empty>
        <slot name="empty"></slot>
      </template>
      <template #append>
        <slot name="append"></slot>
      </template>

      <el-table-column
        v-for="(item, index) in attrs.columns || []"
        :key="index"
        v-bind="item"
        :align="item.align || 'center'"
      >
        <template #default="scope" v-if="item.type !== 'selection'">
          <template v-if="item.slotName">
            <slot :name="item.slotName" :row="scope.row" :scope="scope"></slot>
          </template>
          <template v-else-if="!item.formatter">
            {{
              ([undefined, null].includes(scope.row[item.prop]) && '--') ||
              scope.row[item.prop]
            }}
          </template>
        </template>
      </el-table-column>
      <slot name="default"></slot>
    </el-table>
    <div class="pager-box" v-if="isShowPager">
      <el-pagination
        ref="PaginationRef"
        v-model:current-page="attrs.pager!.page"
        v-model:page-size="attrs.pager!.limit"
        :page-sizes="attrs['page-sizes'] || [10, 20, 30, 50]"
        :total="Number(attrs.total) || 0"
        background
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.pager-box {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
